package complexity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class SequenceList<T> implements Iterable<T>{
    private T[] ele;
    private int N;

    public SequenceList(int capacity) {
        //初始化数组
        this.ele = (T[]) new Object[capacity];
        this.N = 0;
    }

    public void clear() {
        //清空数组
        this.N = 0;
    }

    public boolean isEmpty() {
        return this.N == 0;
    }

    public int length() {
        return this.N;
    }

    public T get(int index) {
        return this.ele[index];
    }

    public void insert(T t) {
        if (this.N==ele.length){
            resize(ele.length*2);
        }
        this.ele[this.N++] = t;
    }

    public void insert(int i, T t) {
        if (this.N==ele.length){
            resize(ele.length*2);
        }
        for (int index=N;index>i;index--){
            ele[index]=ele[index-1];
        }
        ele[i]=t;
        //元素个数加一
        N++;
    }

    public T remove(int i) {
        T current = ele[i];
        for (int index = i;index<N-1;index++){
            ele[index]=ele[index+1];
        }
        --N;
        if (this.N<ele.length/4){
            resize(ele.length/2);
        }
        return current;
    }

    public int indexOf(T t) {
        for (int i = 0; i < N; i++) {
            if (ele[i].equals(t)){
                return i;
            }
        }
        return -1;
    }
    @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }
    public void resize(int newSize){
        T[] temp = ele;
        ele = (T[]) new Object[newSize];
        for (int i = 0; i<N;i++){
            ele[i]=temp[i];
        }
    }
    private class SIterator implements Iterator{
        private int cursor;
        public SIterator(){this.cursor=0;}
        @Override
        public boolean hasNext() {
            return cursor<N;
        }
        @Override
        public Object next() {
            //指针下移一位
            return ele[cursor++];
        }
    }
}
